library(foreign)
library(ggplot2)
library(stargazer)
library(lmtest)
library(dplyr)
library(readr)
library(causalsens)
library(sandwich)
library(caret)
library(purrr)
library(haven)
library(stringr)
library(earth)
library(survey)
library(splines)
library(tidyverse)
library(BART)
setwd("~/Dropbox/Gov_2001_Rep/R Scripts")
source("zmisc.R")

d <- readRDS("CM_cleaned") %>% drop_na()


# Unadjusted ATE
mean(d$dv[d$blacktreatment==1]) - mean(d$dv[d$blacktreatment==0])

#agency index
med.fit <- lm(agency ~ blacktreatment + paternalproframe + paternalnegframe + controlgroup + xideo + xparty7flip + ppeduc, data=apsr_cm, weights=weight2)
summary(med.fit)
out.fit <- lm(dv ~ blacktreatment + agency + paternalproframe + paternalnegframe + controlgroup + xideo + xparty7flip + ppeduc, data=apsr_cm, weights=weight2)
summary(out.fit)
med.out <- mediate(med.fit, out.fit, treat = "blacktreatment", mediator = "agency")
summary(med.out)


A → Y, A → L >SQ Y  , A → M → Y, 

# T > Perception of agency > resentment > foreign aid
# T > Perception of agnecy > perceived lving > resentment


# variable names
x <- c("xideo", "xparty7flip", "ppeduc")
a <- "blacktreatment"
m1 <- "agency"
m2 <- "resentmentindex"
y <- "dv"
m <- list(m1, m2)


# baseline model for overall te
lm_m0 <- lm(dv ~ blacktreatment, weights=weight2, data = d)

# outcome models
Y <- d[[y]]
M1 <- as.matrix(d[, c(x, a, m1)])
M2 <- as.matrix(d[, c(x, a, m1, m2)])
wbart_m1 <- wbart(x.train = M1, y.train = Y)
wbart_m2 <- wbart(x.train = M2, y.train = Y)
ymodels <- list(lm_m0, wbart_m1, wbart_m2)

# paths
library(paths)
paths <- paths(a, y, m, models = ymodels, data = d, nboot = 500)

plot(paths, mediator_names = c("Perception of agency", "Resentment"))






